package com.nl.controller.xuyi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.BaseResult;
import com.nl.controller.common.util.AES;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.global.GlobalConstants;
import com.nl.controller.web.mapper.SmsAreaMapper;
import com.nl.controller.web.mapper.impl.SmsAreaMapperImpl;
import com.nl.controller.web.service.ChangeSynchronizationInterfaceService;
import com.nl.controller.web.service.SmsAreaService;
import com.nl.controller.web.service.SmsMgrTemplateInfoService;
import com.nl.controller.web.util.GZipUtil;
import com.nl.controller.web.util.StringUtil;
import com.nl.controller.xuyi.bean.xuyimap.*;
import com.nl.controller.xuyi.mapper.XuYiMapMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhangheng
 * @Desc:
 * @Date: 16:35 2020/9/8
 * @Modified By:
 */
@Service
@Slf4j
public class XuYiMapService {
    @Autowired
    private SmsMgrTemplateInfoService smsMgrTemplateInfoService;
    @Autowired
    private ChangeSynchronizationInterfaceService changeSynchronizationInterfaceService;
    @Autowired
    private SmsAreaMapperImpl smsAreaMapperImpl;
    @Autowired
    private SmsAreaMapper smsAreaMapper;
    @Autowired
    private XuYiMapMapper xuYiMapMapper;
    @Autowired
    private SmsAreaService smsAreaService;

    @Autowired
    private XuYiStationService xuYiStationService;

    /**
     * desc: 盱眙供电局发送范围同步接口
     * @param req:
     * @return: com.nl.controller.common.model.BaseResult<com.nl.controller.xuyi.bean.xuyimap.SendRangeSynchronizationResp>
     * @author zhangheng
     * @date 2020/9/9 14:55
     */
    public BaseResult<SendRangeSynchronizationResp> sendRangeSynchronization(SendRangeSynchronizationReq req){
        BaseResult<SendRangeSynchronizationResp> result = BaseResult.newFailInstance();
        String sendRangeSynchronizationUrl = GlobalConstants.SEND_RANGE_SYNCHRONIZATION_URL;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mgrId",req.getMgrId());
        jsonObject.put("longAndLatList",req.getLongAndLatList());
        jsonObject.put("stationIds",req.getStationIds());
        jsonObject.put("checkState",req.getCheckState());
        jsonObject.put("mgrState",req.getMgrState());
        jsonObject.put("streamSeq",req.getStreamSeq());
        log.info("sendRangeSynchronization interface request:"+jsonObject.toJSONString());
        try {
            String resp = CommonService.httpPostWithJson(sendRangeSynchronizationUrl, jsonObject);
            //String resp = "1";
            if (!StringUtils.isEmpty(resp)){
                //解压
                resp = GZipUtil.gunzip(resp);
                log.info("sendRangeSynchronization interface response:"+resp);
                //resp = "{\"resultCode\":\"0\",\"stationIds\":\"11111:933992,3929393:999393,93939:333333,999024:121211\",\"mgrId\":\"1000011961\"}";
                JSONObject respJson=JSONObject.parseObject(resp);
                String resultCode = respJson.getString("resultCode");
                if (GlobalConstants.SUCCESS_CODE.equals(resultCode)){
                    String stationIds = respJson.getString("stationIds");
                    String mgrId = respJson.getString("mgrId");
                    //mgrId = req.getMgrId();
                    SendRangeSynchronizationResp sendRangeSynchronizationResp = new SendRangeSynchronizationResp(mgrId,stationIds);
                    result.setRetCode(GlobalConstants.SUCCESS_CODE);
                    result.setData(sendRangeSynchronizationResp);
                } else {
                    String respMsg = StringUtils.isEmpty(respJson.getString("resultDesc")) ? "IT接口提示：获取基站错误" : respJson.getString("resultDesc");
                    result.setRetMsg(respMsg);
                }
            } else {
                result.setRetMsg("IT接口提示：获取基站返回数据为空");
            }
        } catch (Exception e) {
            result.setRetMsg("IT接口异常："+e.getMessage());
        }
        return result;
    }
    /**
     * desc: 记录基站临时表
     * @param resp:
     * @return: java.lang.Integer
     * @author zhangheng
     * @date 2020/9/9 14:54
     */
    private Integer addStationTemp(SendRangeSynchronizationResp resp){
        int stationCount = 0;
        String id =  resp.getMgrId();
        String cityId = "12";
        String regionId = smsAreaService.getRegionId();
        List<String> stationIds = Arrays.asList(resp.getStationIds().split(","));
        if(!StringUtil.isNull(resp.getStationIds())){
            stationCount = stationIds.size();
        }
        List<SmsBaseStation> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(stationIds)){
            for ( String stationId :stationIds ) {
                if(!StringUtil.isNull(stationId)){
                    list.add(new SmsBaseStation(id,regionId,stationId,cityId));
                }
            }
        }
        //先删除临时表中记录
        smsAreaMapper.delStationTemp(id);
        //基站数据记录临时表
        if(CollectionUtils.isEmpty(list)){
            log.info("项目编码："+id+"为无基站项目，无需入基站临时表");
        }else{
            smsAreaMapperImpl.addSmsBaseStationTemp(list);
        }

        return stationCount;
    }
    /**
     * desc: 进行经纬度集合转换，获得GPS坐标经纬度集合
     * @param latList:
     * @return: java.util.List<com.nl.controller.xuyi.bean.xuyimap.LongAndLatsInfo>
     * @author zhangheng
     * @date 2020/9/9 15:03
     */
    private List<LongAndLatsInfo> getLongAndLatList(List<String> latList){
        List<LongAndLatsInfo> longAndLatList = new ArrayList<>();
        try{
            for (String latsInfo: latList) {
                StringBuilder stringBuilder = new StringBuilder();
                String[] split = latsInfo.split("\\+");
                if (split.length==2){
                    String gps = CommonService.BdToGPS(split[0]);
                    stringBuilder.append(gps).append("|").append(split[1]);
                } else {
                    for (int i=0;i<split.length;i++){
                        String gps = CommonService.BdToGPS(split[i]);
                        if (i == split.length-1){
                            stringBuilder.append(gps);
                        } else {
                            stringBuilder.append(gps).append("|");
                        }
                    }
                }
                longAndLatList.add(new LongAndLatsInfo(stringBuilder.toString()));
            }
        } catch (Exception e){
            log.info("获取基站时经纬度转换异常:"+e.getMessage());
            throw new SmsException("获取基站时经纬度转换异常");
        }
        return  longAndLatList;
    }
    
    /**
     * desc: 圈画范围后获取基站
     * @param req:  
     * @return: com.nl.controller.common.model.BaseResult<com.nl.controller.xuyi.bean.xuyimap.XuYiGetStationsResp>
     * @author zhangheng
     * @date 2020/9/9 15:04
     */
    public BaseResult<XuYiGetStationsResp> xuYiGetStations(XuYiGetStationsReq req) {
        BaseResult<XuYiGetStationsResp> result = BaseResult.newFailInstance();
        List<LongAndLatsInfo> longAndLatList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(req.getLongAndLatList())){
            longAndLatList = getLongAndLatList(req.getLongAndLatList());
        }
        try {
        //stations 以','号分隔的基站编码，未加密
        String stations = xuYiStationService.findRelStationByRegion2(req.getPointNameList());
        String aesStations = "";
        if(!StringUtil.isNull(stations)){
            String[] stationsArr =stations.split(",");
            //加密以便直接入库
            for(String station : stationsArr){
                station = AES.encrypt(station, GlobalConst.SKEY);
                if(StringUtil.isNull(aesStations)){
                    aesStations = station;
                }else{
                    aesStations = aesStations + ","+station;
                }
            }
        }

        String mgrId = req.getMgrId();
        if (StringUtils.isEmpty(mgrId)){
            mgrId = smsMgrTemplateInfoService.getMgrId();
        }
        SendRangeSynchronizationReq sendRangeSynchronizationReq = new SendRangeSynchronizationReq();
        sendRangeSynchronizationReq.setMgrId(mgrId);
        sendRangeSynchronizationReq.setCheckState("2");
        sendRangeSynchronizationReq.setLongAndLatList(longAndLatList);
        sendRangeSynchronizationReq.setMgrState("2");
        sendRangeSynchronizationReq.setStationIds(stations);
        sendRangeSynchronizationReq.setStreamSeq(changeSynchronizationInterfaceService.getStreamSeq());
        BaseResult<SendRangeSynchronizationResp> baseResult = sendRangeSynchronization(sendRangeSynchronizationReq);

        String respStationIds = baseResult.getData().getStationIds();
        //拼接所选区域对应加密的基站编码
            if (StringUtils.isEmpty(respStationIds)){
                respStationIds = aesStations;
            } else {
                respStationIds = respStationIds + ","+aesStations;
            }
            //封装返回参数
            baseResult.getData().setStationIds(respStationIds);


        if (GlobalConstants.SUCCESS_CODE.equals(baseResult.getRetCode())){
            SendRangeSynchronizationResp resp = baseResult.getData();
            Integer stationCount = addStationTemp(resp);
            XuYiGetStationsResp data = new XuYiGetStationsResp(resp.getMgrId(),String.valueOf(stationCount));
            result.setRetCode(GlobalConstants.SUCCESS_CODE);
            result.setData(data);
        } else {
            result.setRetMsg(baseResult.getRetMsg());
        }
        }catch (Exception e){
            log.error("xuYiGetStations get a exception "+ e.toString());
            e.printStackTrace();
        }
        return result;
    }
    /**
     * desc: 查询项目发送范围
     * @param req:
     * @return: com.nl.controller.common.model.BaseResult<java.util.List<com.nl.controller.xuyi.bean.xuyimap.QueryRangeResp>>
     * @author zhangheng
     * @date 2020/9/11 10:09
     */
    public BaseResult<List<QueryRangeResp>> queryRange(QueryRangeReq req){
	    BaseResult<List<QueryRangeResp>> result = BaseResult.newFailInstance();
        List<QueryRangeResp> resp = new ArrayList<>();
        try {
            List<QueryRangePo> rangePos = xuYiMapMapper.queryRange(req.getMgrIdList());
            for (QueryRangePo rangePo : rangePos){
                String[] split = rangePo.getRegionTypeValue().split("%_%");
                List<String> linePointNames = JSON.parseArray(split[1], String.class);
                List<String> latitudeAndLongitudes = JSON.parseArray(split[0], String.class);
                List<PointInfo> pointInfos = new ArrayList<>();
                QueryRangeResp queryRangeResp = new QueryRangeResp();
                queryRangeResp .setMgrName(rangePo.getName());
                queryRangeResp.setRange(latitudeAndLongitudes);

                for (String linePointName : linePointNames){
                    int index = linePointName.indexOf("-") + 1;
                    String pointName = linePointName.substring(index);
                    //List<String> latitudeAndLongitude = xuYiMapMapper.getLatitudeAndLongitude(pointName);
                    String bdLngLats = xuYiMapMapper.getLatitudeAndLongitude2(pointName);
                    String[] bdLngLatsArr = bdLngLats.split("\\|");
                    List<String> bdLngLatList = new ArrayList<>();
                    for(String bdLngLat : bdLngLatsArr){
                        bdLngLatList.add(bdLngLat);
                    }

                    pointInfos.add(new PointInfo(linePointName,bdLngLatList));
                }
                queryRangeResp.setPointInfos(pointInfos);
                resp.add(queryRangeResp);
            }
            result.setRetCode(GlobalConstants.SUCCESS_CODE);
            result.setData(resp);
        } catch (Exception e) {
            result.setRetMsg("查询项目发送范围异常："+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public BaseResult<Object> updateRange(UpdateRangeReq req){
        BaseResult<Object> result = BaseResult.newFailInstance();
        try {
            String mgrId = req.getMgrId();
            xuYiMapMapper.updateRange(mgrId,req.getRange());
            smsAreaMapper.delSmsBaseStation(mgrId);
            int insertResult = smsAreaMapper.addStation(mgrId);
            if(insertResult>0){
                smsAreaMapper.delStationTemp(mgrId);
            }
            result.setRetCode(GlobalConstants.SUCCESS_CODE);
        } catch (Exception e){
            result.setRetMsg("更新基站异常："+e.getMessage());
        }
        return result;
    }

}
